package com.ky.study.service.impl;

import com.ky.common.util.AliOssUtil;
import com.ky.study.entity.Static;
import com.ky.study.mapper.StaticMapper;
import com.ky.study.service.StaticService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * 静态资源表 服务实现类
 * </p>
 *
 * @author wgz
 * @since 2024-06-17
 */
@Service
public class StaticServiceImpl extends ServiceImpl<StaticMapper, Static> implements StaticService {
    private String generateObjectName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return System.currentTimeMillis() + "_" + originalFilename;
    }

    @Override
    public ResponseEntity<String> uploadFile(MultipartFile file) {
        try {
            // 将MultipartFile转换为字节数组
            byte[] fileData = file.getBytes();

            // 直接调用工具类的静态方法进行上传
            String imageUrl = AliOssUtil.uploadByte("gp-kaoyan", generateObjectName(file), fileData);

            System.out.println(imageUrl);
            // 将图片URL在？处进行分割
            String[] imageUrls = imageUrl.split("\\?");
            System.out.println(imageUrls[0]);
            return ResponseEntity.ok(imageUrl); // 返回图片URL
        } catch (IOException e) {
            // 处理文件读取或转换异常
            throw new MultipartException("Failed to read or process the uploaded file", e);
        }
    }
}
